package com.wstuo.itsm.cim.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.category.dao.ICICategoryDAO;
import com.wstuo.common.config.category.entity.CICategory;
import com.wstuo.common.config.category.service.ICICategoryService;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.security.utils.AppContext;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.tools.service.IExportInfoService;
import com.wstuo.itsm.cim.dto.SimpleFileDTO;
import com.wstuo.itsm.cim.entity.CI;
import com.wstuo.itsm.cim.util.CIImportUtil;

/**
 * 原本位置 exportTemplateAction!createTemplateWithCategory.action?categoryNo=0
 * 迁移过来了；
 * @author gs60
 *
 */
public class ImportCIService implements IImportCIService {
	final static Logger LOGGER = Logger.getLogger(ImportCIService.class);
	private final static String ATTR_FILED_IDENTITY = "['%s']";
	
	private static List<String> fixedCol = null;//添加导入固定字段
	@Autowired
	private AppContext appctx;
	@Autowired
    private ICICategoryService cicategoryService;
	@Autowired
	private ICICategoryDAO cicategoryDAO;
	@Autowired
	private IExportInfoService exportInfoService;
	
	/**
	 * 生成配置项csv表格模板
	 */
	@Transactional
	public SimpleFileDTO generateTemplateWithCategory(Long categoryNo) {
		SimpleFileDTO fileDTO = new SimpleFileDTO();
		CICategory ciCategory = cicategoryDAO.findCICategoryById(categoryNo);
		if( ciCategory == null ){
			return fileDTO;
		}
		String categoryName = cicategoryService.findCategoryNameIncludParent(ciCategory,null);
		fileDTO.setFileName(categoryName,IExportInfoService.FILE_EXTENSION);
		
		String path = AppConfigUtils.getInstance().getConfigPathByTenantId(
				"exportFilePath", "exportFile", appctx.getCurrentTenantId());
		
		File dir = new File(path);if( dir.isDirectory() && !dir.exists() ){ dir.mkdirs(); }
		
		String filePath = path + File.separator + categoryName + IExportInfoService.FILE_EXTENSION;
		exportInfoService.exportCSV(filePath , generateExportData( ciCategory ) );
		try {
			File file = new File(filePath);
   			if( file != null && file.exists()){
   	   	   		fileDTO.setInputStream(new FileInputStream(file)) ;
   			}
		} catch (FileNotFoundException e) {
			LOGGER.error(e);//e.printStackTrace();
		}
		return fileDTO;
	}
	/**
	 * 生成导出文件的表头字段
	 * @param formCustom
	 * @return
	 */
	private List<String[]> generateExportData(CICategory ciCategory ){
		List<String> fields = new ArrayList<String>();
		//基础字段
		List<String> basicFields = getBasicField(fixedCol, getDefaultTemplate() 
				+ "/ConfigureItem.properties", IExportInfoService.STRING_SEPARATOR );
		if ( basicFields != null ) {
			fixedCol = basicFields;//下次就不用再读取了
			fields.addAll(basicFields);
		}
		//自定义字段
		//List<CI> attrList = null;
		List<String> attrFields = getAttrFields(null, IExportInfoService.STRING_SEPARATOR);
		if( attrFields != null){
			fields.addAll(attrFields);
		}
		String[] data = fields.toArray(new String[ fields.size() ]);
		//因为导出CSV表头时，只有一行，所以将数据转换成数组；
		List<String[]> datas = new ArrayList<String[]>();
		if( data != null ){
			datas.add(data);
		}
		return datas;
	}
	
	/**
	 * 获取基础表单
	 * @param fixedCol
	 * @param filePath
	 * @param separator
	 * @return
	 */
	private List<String> getBasicField(List<String> fixedCol
			,final String filePath,final String separator){
		if( fixedCol == null ){
			List<String> fields = new ArrayList<String>();
			LanguageContent lc = LanguageContent.getInstance();
			LinkedHashMap<String, String> col = CIImportUtil.readPropertiesFile( filePath);
			if( col != null && col.size() > 0 ){
				Iterator<String> iter = col.keySet().iterator(); 
				while (iter.hasNext()) { 
					String key = iter.next();
					fields.add( lc.getContent(key) + separator + col.get(key) );
				}
			}
			return fields;
		}else{
			return fixedCol;
		}
	}
	/**
	 * 自定义类型转换为导入模板的表头
	 * @param attrFields
	 * @param separator
	 * @return
	 */
	private List<String> getAttrFields(final List<CI> attrFields,final String separator){
		List<String> list = new ArrayList<String>();
		/*if( attrFields != null){
			for (Attribute attr : attrFields) {
				StringBuffer buffer = 
						new StringBuffer(attr.getAttrAsName())
						.append(separator)
						.append(CIImportUtil.FILED_IDENTITY)
						.append(String.format(ATTR_FILED_IDENTITY, attr.getAttrName()) )
					;
				list.add( buffer.toString() );
			}
		}*/
		return list;
	}
	/**
	 * 获取默认导入文件的位置
	 * @return
	 */
	private String getDefaultTemplate(){
   		//String path = this.getClass().getResource("/").getPath();//指向classes
		String path = AppConfigUtils.getInstance().getConfigPath("", "importFile/");
		/*String lang = appctx.getCurrentLanguage() ;
		lang = "/zh_CN"  + lang ;*/
		return path ;
	}
}
